<?php
/**
 * Created by PhpStorm.
 * User: caviar
 * Date: 2019/11/1
 * Time: 16:58
 */

namespace app\lib\redis;


use app\lib\exception\ServiceErrorException;
use think\cache\driver\Redis;
use think\facade\Log;

/** redis 分布式锁 */
class Lock
{
    //redis 实例
    private $redis;

    //redis key
    private $key;

    /**
     * RedisServer constructor.
     * @param $key
     * @throws ServiceErrorException
     */
    public function __construct($key)
    {
        $this->redis = new Redis();
        $this->key = $key."_lock";
        $this->isLock();
    }

    /** 开始锁 */
    public function aLock()
    {
        $this->redis->set($this->key,'true');
        Log::record($this->key.'开始锁');
        Log::save();
    }

    /**
     * 判断锁
     * @throws ServiceErrorException
     */
    public function isLock()
    {
        $value = $this->redis->get($this->key);
        if (!empty($value)) {
            throw new ServiceErrorException('资源被锁住!',500);
        }
    }

    /** 释放锁 */
    public function unLock()
    {
        $this->redis->rm($this->key);
        Log::record($this->key."Lock out");
        Log::save();
    }

}